const app = getApp();

import { 
    uploadAvatar, 
    sendRegisterSmsCode,
    registerUser,
    handleUser,
    getUserInfoBySysID  
} from "../../../api/my_v1";
import calendar from "../../../static/js/calendar";
import Notify from '@vant/weapp/notify/notify';
import dayjs from "dayjs";
Page({
  data: {
    actionType: "edit",
    app: app,
    userInfo: {
      userSysID: -1,
      gender: 1, //1男2女
      nickName: "",
      birthday: "",
      lunarBirthday: "",
      lunarOrSolar: "1",
      mobile: "",
      avatarUrl: "",
      smscode:""
    },
    error: {
      nickName_show: false,
      nickName_message: "请输入昵称",
      birthday_show: false,
      birthday_message: "请选择生日",
      mobile_show: false,
      mobile_message: "请输入手机号",
      smscode_show:false,
      smscode_message:"请输入验证码"
    },
    date: {
      show: false,
      horoscope: "",
      lunarNumBirthday: "",
      solarBirthday: "",
    },
    loading: false,
    smscode:{
        text:'发送验证码',
        disabled:false
    }
  },
  onLoad(options) {
    let actionType = options.actionType;
    this.setData({
      actionType: actionType,
    });
    if (actionType === "edit") {
      wx.setNavigationBarTitle({
        title: "编辑用户",
      });
      this.GetUserInfo();
    } else {
      wx.setNavigationBarTitle({
        title: "注册用户",
      });
    }
  },
  GetUserInfo() {
    let reqData = {
      UserSysID: app.globalData.userInfo.userSysID,
    };
    getUserInfoBySysID(reqData)
        .then(({ code, data }) => {
            if (code === 200) {
                let {
                    UserSysID,
                    Gender,
                    NickName,
                    Birthday,
                    LunarBirthday,
                    LunarOrSolar,
                    Mobile,
                    AvatarUrl,
                } = data;
                let userInfo = {
                    userSysID: UserSysID,
                    gender: Gender, //1男2女
                    nickName: NickName,
                    birthday: Birthday,
                    lunarBirthday: LunarBirthday,
                    lunarOrSolar: LunarOrSolar,
                    mobile: Mobile,
                    avatarUrl: AvatarUrl,
                };
                this.setData({
                    userInfo: userInfo,
                });
            }
        });
  },
  //切换性别
  onChangeGender(e) {
    let gender = e.currentTarget.dataset.gender;
    if (gender !== this.data.userInfo.gender) {
      this.setData({
        "userInfo.gender": gender,
      });
    }
  },
  onChangeField(e) {
    let field = e.currentTarget.dataset.field;
    switch (field) {
      case "nickName":
        this.setData({
          "userInfo.nickName": e.detail,
          "error.nickName_show": false,
        });
        break;
      case "mobile":
        this.setData({
          "userInfo.mobile": e.detail,
          "error.mobile_show": false,
        });
        break;
    case "smscode":
        this.setData({
            "userInfo.smscode": e.detail,
            "error.smscode_show": false,
        });
        break;
      default:
        break;
    }
  },
  onBlurField(e) {
    let field = e.currentTarget.dataset.field;
    let value = e.detail.value;
    this.VerificationField(field, value);
  },
  VerificationField(field, value) {
    let flag = true;
    switch (field) {
      case "nickName":
        if (value.trim() === "") {
          flag = false;
          this.setData({
            "error.nickName_show": true,
          });
        }
        break;
      case "birthday":
        if (value.trim() === "") {
          flag = false;
          this.setData({
            "error.birthday_show": true,
          });
        }
        break;
      case "mobile":
        let reg = /^(?:(?:\+|00)86)?1\d{10}$/;
        if (value.trim() === "") {
          flag = false;
          this.setData({
            "error.mobile_show": true,
            "error.mobile_message": "请输入手机号",
          });
        } else if (!reg.test(value)) {
          flag = false;
          this.setData({
            "error.mobile_show": true,
            "error.mobile_message": "手机号格式有误!",
          });
        }
        break;
    case "smscode":
        if (value.trim() === "") {
            flag = false;
            this.setData({
                "error.smscode_show": true,
            });
        }
        break;
      default:
        break;
    }
    return flag;
  },
  onClickSelectBirthday() {
    this.setData({
      "date.show": true,
    });
  },
  onChangeLunar(e) {
    this.setData({
      "userInfo.lunarOrSolar": e.detail.lunar ? "0" : "1",
    });
  },
  onHideDate() {
    this.setData({
      "date.show": false,
    });
  },
  onConfirmBirthday(e) {
    let dayInfo = e.detail.dayInfo;
    let birthday = dayInfo.date;
    let { date, lunarDate, IMonthCn, IDayCn, astro } = calendar.solar2lunar(
      dayjs(birthday).format("YYYY"),
      dayjs(birthday).format("MM"),
      dayjs(birthday).format("DD")
    );
    let dateInfo = {
      show: false,
      horoscope: astro === "魔羯座" ? "摩羯座" : astro,
      lunarNumBirthday: dayjs(lunarDate).format("MM-DD"),
      solarBirthday: dayjs(date).format("MM-DD"),
    };
    this.setData({
      "error.birthday_show": false,
      date: dateInfo,
      "userInfo.birthday": dayjs(date).format("YYYY-MM-DD"),
      "userInfo.lunarBirthday": IMonthCn + IDayCn,
      "userInfo.birthday": dayjs(date).format("YYYY-MM-DD"),
    });
  },
  onClickRegister() {
      let that=this;
      if(this.data.userInfo.avatarUrl===''){
        Notify({ type: "danger", message: '请上传头像' });
      }
    else if (
      this.VerificationField("nickName", this.data.userInfo.nickName) &&
      this.VerificationField("birthday", this.data.userInfo.birthday) &&
      this.VerificationField("mobile", this.data.userInfo.mobile)&&
      this.VerificationField("smscode", this.data.userInfo.smscode)
    ) {
      let birthday = this.data.userInfo.birthday;
      let { lunarDate, IMonthCn, IDayCn, astro } = calendar.solar2lunar(
        dayjs(birthday).format("YYYY"),
        dayjs(birthday).format("MM"),
        dayjs(birthday).format("DD")
      );
      let reqData = {
        OpenID: app.globalData.openId,
        UserSysID: this.data.userInfo.userSysID,
        NickName: this.data.userInfo.nickName,
        Birthday: this.data.userInfo.birthday,
        LunarBirthday: IMonthCn + IDayCn,
        LunarNumBirthday: dayjs(lunarDate).format("MM-DD"),
        SolarBirthday: dayjs(birthday).format("MM-DD"),
        LunarOrSolar: this.data.userInfo.lunarOrSolar,
        Mobile: this.data.userInfo.mobile,
        Gender: this.data.userInfo.gender,
        AvatarUrl: this.data.userInfo.avatarUrl,
        Horoscope: astro,
        SmsCode:this.data.userInfo.smscode
      };
      this.setData({
        loading: true,
      });
      if (this.data.actionType === "edit") {
        handleUser(reqData)
            .then(({ code, msg, data }) => {
                this.setData({
                    loading: false,
                });
                if (code === 200) {
                    //编辑
                    let userInfo = {
                        userSysID: app.globalData.userInfo.userSysID,
                        nickName: that.data.userInfo.nickName,
                        avatarUrl: that.data.userInfo.avatarUrl,
                    };
                    app.globalData.userInfo = userInfo;
                    wx.setStorage({
                        key: "userInfo",
                        data: JSON.stringify(userInfo),
                    });
                    Notify({ type: "success", message: "保存成功!" });
                    wx.navigateBack({
                        delta: 1,
                    });
                } else {
                    Notify({ type: "danger", message: msg });
                }
            })
            .catch(()=>{
                this.setData({
                    loading: false,
                });
            })
      }
      else{
        registerUser(reqData)
            .then(({ code, msg, data }) => {
                this.setData({
                loading: false,
                });
                if (code === 200) {
                    //注册
                    let { UserSysID = -1 } = data;
                    let userInfo = {
                        userSysID: UserSysID,
                        nickName: that.data.userInfo.nickName,
                        avatarUrl: that.data.userInfo.avatarUrl,
                    };
                    app.globalData.userInfo = userInfo;
                    wx.setStorage({
                        key: "userInfo",
                        data: JSON.stringify(userInfo),
                    });
                    wx.redirectTo({
                        url: "../otherHalf/otherHalf",
                    });
                } else {
                    Notify({ type: "danger", message: msg });
                }
            })
            .catch(()=>{
                this.setData({
                    loading: false,
                });
            })
      }
    }
  },
  onClickSendSms(){
    //   发送验证码
    let reg = /^(?:(?:\+|00)86)?1\d{10}$/;
    if (this.data.userInfo.mobile.trim() === "") {
        this.setData({
            "error.mobile_show": true,
        });
    }
    else if (!reg.test(this.data.userInfo.mobile)) {
        this.setData({
          "error.mobile_show": true,
          mobile_message: "手机号格式有误!",
        });
    }
    else{
        let time=60;
        this.setData({
            smscode:{
                text:time+'秒后重新发送',
                disabled:true
            }
        })
        let smscodeInterval= setInterval(()=>{
            time=time-1;
            if(time>0){
                this.setData({
                    smscode:{
                        text:time+'秒后重新发送',
                        disabled:true
                    }
                })
            }
            else{
                clearInterval(smscodeInterval)
                this.setData({
                    smscode:{
                        text:'重新发送验证码',
                        disabled:false
                    }
                })
            }
        },1000)
        let reqData={
            Phone:this.data.userInfo.mobile
        }
        sendRegisterSmsCode(reqData)
            .then(res=>{})
    }
    
  },
  async onClickChooseAvatar(e){
    const response = await this.UploadImgToBase64(e.detail.avatarUrl);
    let reqData={
        AvatarFile:response.data
    }
    uploadAvatar(reqData)
        .then(({code,data,msg})=>{
            if(code===200){
                this.setData({
                    'userInfo.avatarUrl':data.ImageUrl
                })
            }
            else{
                Notify({ type: "danger", message: msg });
            }
        })
        .catch(e=>{
            Notify({ type: "danger", message: '上传头像失败!' });
        })
  },
    UploadImgToBase64(file) {
        return new Promise((resolve,reject) => {
            wx.getFileSystemManager()
                .readFile({
                    filePath: file,
                    encoding: 'base64',
                    success: res => {
                        return resolve(res)
                    },
                    fail(res) {
                        return reject(res)
                    }
                })
        })
    },
});
